package com.derbysoft.dswitch.adapter.ihg.common.repository.impl;

import com.derbysoft.dswitch.adapter.ihg.common.domain.FreeMealStrategy;
import com.derbysoft.dswitch.adapter.ihg.common.repository.FreeMealStrategyRepository;
import com.derbysoft.dswitch.adapter.ihg.web.action.support.Paginater;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * User: jason
 * Date: 2013-01-05
 */
@Repository("freeMealStrategyRepository")
public class FreeMealStrategyRepositoryImpl extends CommonService<FreeMealStrategy>
        implements FreeMealStrategyRepository {

    @Override
    public void saveAll(List<FreeMealStrategy> freeMealStrategies) {
        for (FreeMealStrategy freeMealStrategy : freeMealStrategies) {
            super.commonDao.save(freeMealStrategy);
        }
    }

    @Override
    public Paginater paginater(FreeMealStrategy freeMealStrategy, Paginater paginater) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(FreeMealStrategy.class).addOrder(Order.desc("id"));
        if (freeMealStrategy == null) {
            return super.paginater(detachedCriteria, paginater);
        }
        if (StringUtils.isNotBlank(freeMealStrategy.getChannelPattern())) {
            detachedCriteria.add(Restrictions.eq("channelPattern", freeMealStrategy.getChannelPattern()));
        }
        if (StringUtils.isNotBlank(freeMealStrategy.getHotelPattern())) {
            detachedCriteria.add(Restrictions.eq("hotelPattern", freeMealStrategy.getHotelPattern()));
        }
        if (StringUtils.isNotBlank(freeMealStrategy.getRatePlanPattern())) {
            detachedCriteria.add(Restrictions.eq("ratePlanPattern", freeMealStrategy.getRatePlanPattern()));
        }
        if (StringUtils.isNotBlank(freeMealStrategy.getRoomTypePattern())) {
            detachedCriteria.add(Restrictions.eq("roomTypePattern", freeMealStrategy.getRoomTypePattern()));
        }
        return paginater(detachedCriteria, paginater);
    }

    @Override
    public FreeMealStrategy load(String channel, String hotel, String ratePlan, String roomType) {
        return load(new String[]{"channelPattern", "hotelPattern", "ratePlanPattern", "roomTypePattern"},
                new Object[]{channel, hotel, ratePlan, roomType});
    }
}
